var roomService = require('../service/room');
var ConstCode = require('../constant/ConstCode');

async function getRoomList(req, res) {
  var data = await roomService.getRoomList();
  return res.send({
    code: ConstCode.SUCCESS_CODE,
    data
  });
};

async function joinRoom(req, res) {
  var { roomid, type } = req.query;
  var userid = req.session.userid;
  var data = await roomService.joinRoom(roomid, userid, type);
  return res.send({
    code: ConstCode.SUCCESS_CODE,
    data
  });
}

async function ready(req, res) {
  var { roomid, type } = req.query;
  var userid = req.session.userid;
  var username = req.session.username;
  var data = await roomService.ready(roomid, type, userid, username);
  return res.send({
    code: ConstCode.SUCCESS_CODE,
    data
  });
}

async function getRoomById(req, res) {
  var { roomid } = req.query;
  var userid = req.session.userid; 
  var data = await roomService.getRoomById(roomid);
  if (userid == data.blackUser) {
    data.type = 'H';
  } else if (userid == data.whiteUser) {
    data.type = 'B';
  }
  return res.send({
    code: ConstCode.SUCCESS_CODE,
    data
  });
}

async function addStep(req, res) {
  var { x, y, type, roomid } = req.query;
  var userid = req.session.userid;
  var data = await roomService.addStep(x, y, type, userid, roomid);
  return res.send({
    code: ConstCode.SUCCESS_CODE,
    data
  });
}

async function getSteps(req, res) {
  var { roomid } = req.query;
  // var userid = req.session.userid;
  var data = await roomService.getSteps(roomid);
  return res.send({
    code: ConstCode.SUCCESS_CODE,
    data
  });
}

async function creatRoom(req, res) {
  var userid = req.session.userid;
  var username = req.session.username;
  var { chessSize, letNum, color, roomname } = req.query;
  var blackUser = color == 'H' ? userid : null;
  var whiteUser = color == 'B' ? userid : null;
  var result = await roomService.creatRoom(
    roomname,
    userid, 
    blackUser,
    whiteUser,
    chessSize,
    letNum,
    username
  );
  return res.send({
    code: ConstCode.SUCCESS_CODE,
    data: result
  });
};

module.exports = {
  getRoomList,
  joinRoom,
  ready,
  getRoomById,
  addStep,
  getSteps,
  creatRoom
};
